using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Vibstudio.X4NET.IO.INI.Model
{
    public class SectionDataCollection : ICloneable, IEnumerable<SectionData>
    {
        #region Initialization

        public SectionDataCollection()
        {
            _sectionData = new Dictionary<string, SectionData>(StringComparer.InvariantCultureIgnoreCase);
        }

        public SectionDataCollection(SectionDataCollection ori)
        {
            _sectionData = new Dictionary<string, SectionData>(ori._sectionData, StringComparer.InvariantCultureIgnoreCase);
        }

        #endregion

        #region Properties

        public int Count
        {
            get { return _sectionData.Count; }
        }

        public KeyDataCollection this[string sectionName]
        {
            get { return _sectionData.ContainsKey(sectionName) ? _sectionData[sectionName].Keys : null; }
        }

        #endregion

        #region Public Members

        public bool AddSection(string keyName)
        {
            if (!ContainsSection(keyName))
            {
                _sectionData.Add(keyName, new SectionData(keyName));
                return true;
            }

            return false;
        }

        public bool ContainsSection(string keyName)
        {
            return _sectionData.ContainsKey(keyName);
        }

        public SectionData GetSectionData(string sectionName)
        {
            return _sectionData.ContainsKey(sectionName) ? _sectionData[sectionName] : null;
        }

        public void SetSectionData(string sectionName, SectionData data)
        {
            if (data != null)
            {
                _sectionData[sectionName] = data;
            }
        }

        public bool RemoveSection(string keyName)
        {
            return _sectionData.Remove(keyName);
        }

        public void Clear()
        {
            _sectionData.Clear();
        }

        #endregion

        #region IEnumerable<SectionData> Members

        public IEnumerator<SectionData> GetEnumerator()
        {
            return _sectionData.Keys.Select(sectionName => _sectionData[sectionName]).GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion

        #region ICloneable Members

        public object Clone()
        {
            return new SectionDataCollection(this);
        }

        #endregion

        #region Non-public Members

        private readonly Dictionary<string, SectionData> _sectionData;

        #endregion
    }
}